import JSBridgeClient from '../base/js-bridge-client'

// eslint-disable-next-line no-unused-vars
const SUCCESS_CODE = '000000'

const BaseModule  = {
  randomString(e) {
    e = e || 32
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz12345678",
        a = t.length,
        n = "";
    for (var i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n
  },
  /**
   * 通过listener监听客户端回调
   * @param action
   * @param params
   * @returns {Promise<object>}
   */
  fireEventForAsync(action, params = {}) {
    return new Promise((resolve, reject) => {
      const listener = `${action}Listener${this.randomString()}`
      window[listener] = (result) => {
        let response = result
        if (typeof response === 'string') {
          response = JSON.parse(response)
        }
        if (
            response.ReturnCode &&
            response.ReturnCode !== SUCCESS_CODE
        ) {
          if (reject) {
            return reject(response)
          }
        }
        if (resolve) {
          return resolve(response)
        }
      }
      JSBridgeClient
        .bridge('CSIIBridge', {
          action,
          listener,
          params,
        })
    })
  }
}

export default BaseModule
